package cn.devcat.sso.service.mail;

import cn.devcat.sso.entity.DevcatUser;
import cn.devcat.sso.service.ISendMailService;
import cn.devcat.sso.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Random;

@Service("findPassword")
public class SendFindPasswordEmail implements ISendMailService {

	@Autowired
	JavaMailSender mailSender;

	@Autowired
	RedisUtil redisUtil;

  @Value("${devcat.save-file-path}")
  private String saveFilePath;

	@Override
	public void sendMail(DevcatUser userByRequest) throws MessagingException {
		// TODO Auto-generated method stub
		String toEmail = userByRequest.getEmail();
		MimeMessage message = mailSender.createMimeMessage();
		MimeMessageHelper helper = new MimeMessageHelper(message, true);
		helper.setFrom("admin@devcat.cn");
		helper.setTo(toEmail);
		helper.setSubject("Devcat-密码找回");
		String content = getRegisterHtmlStr(userByRequest);
		helper.setText(content, true);
		mailSender.send(message);
	}

	private String getRegisterHtmlStr(DevcatUser user) {
		char[]enableCode = makeEnableCode();
		StringBuilder content = new StringBuilder();
        try(BufferedReader reader = new BufferedReader(new FileReader(saveFilePath+"mail/findpassword.html"))){
            String temp;
            while((temp = reader.readLine()) != null){
                if(temp.contains("${num1}")) {
                	temp = temp.replace("${num1}", String.valueOf(enableCode[0]));
                }
                if(temp.contains("${num2}")) {
                	temp = temp.replace("${num2}", String.valueOf(enableCode[1]));
                }
                if(temp.contains("${num3}")) {
                	temp = temp.replace("${num3}", String.valueOf(enableCode[2]));
                }
                if(temp.contains("${num4}")) {
                	temp = temp.replace("${num4}", String.valueOf(enableCode[3]));
                }
                content.append(temp);
            }
            redisUtil.insertOfString("find:"+user.getUsername(), String.valueOf(enableCode), 10*60);
        }catch (IOException e){
            e.printStackTrace();
        }
        return content.toString();
	}

	private char[] makeEnableCode() {
		char[]bases = {'d','e','v','c','a','t','0','1','2','3','4','5','6','7','8','9','@'};
		char[]result = new char[4];
		Random random = new Random();
		for(int i=0; i<4; i++) {
			result[i] = bases[random.nextInt(bases.length)];
		}
		return result;
	}

}
